package com.atguigu.tingshu.album.receiver;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * ClassName : AlbumReceiver
 * Package : com.atguigu.tingshu.album.receiver
 * Description :
 * <p>
 * Author: LHZ
 * Create: 2025/7/28 17:19
 * Version: 1.0
 */
@Slf4j
@Component
public class AlbumReceiver {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 监听到更新声音统计数值MQ消息
     *
     * @param vo
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK,durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(TrackStatMqVo vo, Channel channel, Message message){
        if(vo != null){
            log.info("更新声音统计：{}", vo);
            //对消费者进行消息幂等性处理
            String redisKey = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + "db:" + vo.getBusinessNo();
            Boolean isFlag = redisTemplate.opsForValue().setIfAbsent(redisKey, "1", 3, TimeUnit.MINUTES);
            if(isFlag){
                try {
                    trackInfoService.updateTrackStat(vo);
                } catch (Exception e) {
                    redisTemplate.delete(redisKey);
                    //拒绝当前消息,且不放回队列(不重试) -> 后续交给人工处理
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                }
            }
        }
        //手动确认消息已经被成功处理,可以从队列中删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}